<template>
  <div class="shopCart">
    <div class="title">
      <span></span>
      <p>购物车</p>
      <span @click="administration" v-if="normalState">管理</span>
      <span @click="normalState = true" v-if="!normalState">完成</span>
    </div>
    <div class="content" v-if="!empty">
      <ul class="list" v-if="shopCartGoods">
        <li
          v-for="(item, index) in shopCartGoods.storeCartGroupList"
          :key="index"
        >
          <div
            class="store-title"
            @click="
              $router.push({
                path: '/store',
                query: { storeid: item.storeId },
              })
            "
          >
            <img
              src="	https://image-mall.gxptkc.com/m/resources/shop/shop_icon.png"
              alt=""
            />
            <p>{{ item.storeName }}</p>
            <span>&gt;</span>
          </div>
          <ul class="goods-content">
            <li
              v-for="(i, index) in item.promotionCartGroupList[0].cartList"
              :key="index"
              @click="
                $router.push({
                  path: '/product',
                  query: { goodsId: i.goodsId, productId: i.productId },
                })
              "
            >
              <input
                type="radio"
                @click.stop="changeCartGoods(i.cartId, i.isChecked)"
                :checked="i.isChecked"
                class="radio_type"
              />
              <img :src="i.productImage" alt="" />
              <div class="detail">
                <div class="detail-title">
                  <p>{{ i.goodsName }}</p>
                  <span>{{ i.specValues }}</span>
                </div>
                <div class="detail-action">
                  <span>￥{{ i.productPrice.toFixed(2) }}</span>
                  <div class="stepper">
                    <span @click.stop="decGoods(i.cartId, i.buyNum)">-</span>
                    <input type="text" :value="i.buyNum" />
                    <span @click.stop="addGoods(i.cartId, i.buyNum)">+</span>
                  </div>
                </div>
              </div>
            </li>
          </ul>
        </li>
      </ul>
      <div class="empty" v-if="empty">
        <img
          src="https://image-mall.gxptkc.com/m/resources/empty_goods.png"
          alt=""
        />
        <p>这里空空如也~快去商品中心加购商品吧！</p>
        <button @click="$router.push({ path: '/goods' })">马上去逛逛</button>
      </div>
    </div>
    <EmptyView v-if="empty" />
    <RecommentGoods />
    <div class="balance" v-if="!empty">
      <div class="left">
        <input
          class="radio_type"
          type="radio"
          name=""
          id=""
          :checked="shopCartGoods.checkedAll"
          @click="totalGoods(shopCartGoods.checkedAll)"
        />
        <span>全选</span>
      </div>
      <div class="right" v-if="normalState">
        <span>合计:</span>
        <span>￥{{ settlement.toFixed(2) }}</span>
        <button @click="toSettlement(shopCartGoods.totalCheck)">
          结算{{ shopCartGoods.totalCheck }}
        </button>
      </div>
      <div class="right-del-cart" v-if="!normalState">
        <span @click="movetoCollection">加入收藏夹</span>
        <span @click="delCart">删除所选</span>
      </div>
    </div>
    <div class="bottom"></div>
  </div>
</template>

<script>
import qs from "qs";
import RecommentGoods from "@/components/RecommentGoods.vue";
import EmptyView from "@/components/EmptyView.vue";
import { Toast } from "vant";
export default {
  components: { RecommentGoods, EmptyView },

  data() {
    return {
      shopCartGoods: [],
      token: null,
      settlement: 0,
      checked: 0,
      empty: true,
      normalState: true,
      checkid: [],
    };
  },
  methods: {
    toSettlement(num) {
      if (num > 0) {
        this.$router.push({
          path: "/confirm",
          query: { cartIds: JSON.stringify(this.checkid) },
        });
      } else {
        Toast.fail("请选择商品！");
      }
    },
    administration() {
      if (!this.empty) {
        this.normalState = false;
      }
    },
    async movetoCollection() {
      let res = await this.axios({
        method: "POST",
        url: "https://m-mall.gxptkc.com/v3/business/front/cart/moveToCollection",
        headers: {
          authorization: `Bearer ${this.token}`,
          "content-type": "application/x-www-form-urlencoded",
        },
        data: qs.stringify({
          cartIds: this.checkid.join(","),
        }),
      });
      Toast(res.data.msg);
      if (res.data.msg == "成功") {
        this.requestCart();
      }
    },
    async delCart() {
      let res = await this.axios({
        method: "POST",
        url: "https://m-mall.gxptkc.com/v3/business/front/cart/deleteCarts",
        headers: {
          authorization: `Bearer ${this.token}`,
          "content-type": "application/x-www-form-urlencoded",
        },
        data: qs.stringify({
          cartIds: this.checkid.join(","),
        }),
      });
      Toast(res.data.msg);
      if (res.data.msg == "成功") {
        this.requestCart();
      }
    },
    async requestCart() {
      let res = await this.axios({
        method: "GET",
        url: "https://m-mall.gxptkc.com/v3/business/front/cart/cartList",
        headers: {
          authorization: `Bearer ${this.token}`,
        },
      });
      if (res.data.msg == "成功") {
        this.shopCartGoods = res.data.data;
        this.settlement = res.data.data.totalAmount;
      } else {
        console.log("请登录");
      }
    },
    async decGoods(cartId, num) {
      num--;
      await this.axios({
        method: "POST",
        url: "https://m-mall.gxptkc.com/v3/business/front/cart/changeNum",
        headers: {
          authorization: `Bearer ${this.token}`,
        },
        data: qs.stringify({
          cartId: cartId,
          number: num,
        }),
      });
      this.requestCart();
    },
    async addGoods(cartId, num) {
      num++;
      await this.axios({
        method: "POST",
        url: "https://m-mall.gxptkc.com/v3/business/front/cart/changeNum",
        headers: {
          authorization: `Bearer ${this.token}`,
        },
        data: qs.stringify({
          cartId: cartId,
          number: num,
        }),
      });
      this.requestCart();
    },
    async changeCartGoods(cartId, check) {
      if (check) {
        this.checked = 0;
        this.checkid = this.checkid.filter((o) => o != cartId);
      } else {
        this.checked = 1;
        this.checkid = [cartId, ...this.checkid];
      }
      await this.axios({
        method: "POST",
        url: "https://m-mall.gxptkc.com/v3/business/front/cart/checkedCarts",
        headers: {
          authorization: `Bearer ${this.token}`,
        },
        data: qs.stringify({
          cartIds: cartId,
          checked: this.checked,
        }),
      });
      this.requestCart();
    },
    async totalGoods(check) {
      let ids = this.shopCartGoods.storeCartGroupList.map((o) => {
        return o.promotionCartGroupList[0].cartList.map((p) => {
          return p.cartId;
        });
      });
      let arrId = [];
      ids.forEach(function (i) {
        arrId.push(...i);
      });
      if (check) {
        this.checked = 0;
      } else {
        this.checked = 1;
      }
      await this.axios({
        method: "POST",
        url: "https://m-mall.gxptkc.com/v3/business/front/cart/checkedCarts",
        headers: {
          authorization: `Bearer ${this.token}`,
        },
        data: qs.stringify({
          cartIds: arrId.join(","),
          checked: this.checked,
        }),
      });
      this.requestCart();
    },
  },
  async created() {
    this.token = localStorage.getItem("fastCar-token");
    let res = await this.axios({
      method: "GET",
      url: "https://m-mall.gxptkc.com/v3/business/front/cart/cartList",
      headers: {
        authorization: `Bearer ${this.token}`,
      },
    });
    if (res.data.msg == "成功" && res.data.data.availableCartNum > 0) {
      this.shopCartGoods = res.data.data;

      this.settlement = res.data.data.totalAmount;

      this.empty = false;

      //处理出被选中的商品
      let arr = this.shopCartGoods.storeCartGroupList;
      arr.forEach((o) => {
        o?.promotionCartGroupList[0]?.cartList.forEach((i) => {
          if (i.isChecked) {
            this.checkid = [i.cartId, ...this.checkid];
          }
        });
      });
    } else {
      this.empty = true;
    }
  },
};
</script>

<style lang="scss" scoped>
.radio_type {
  width: 20px;
  height: 20px;
  appearance: none;
  position: relative;
}
.radio_type:before {
  content: "";
  width: 20px;
  height: 20px;
  border: 1px solid #7d7d7d;
  display: inline-block;
  border-radius: 50%;
  vertical-align: middle;
}
.radio_type:checked:before {
  content: "";
  width: 20px;
  height: 20px;
  border: 1px solid #fc1c1c;
  background: #fc1c1c;
  display: inline-block;
  border-radius: 50%;
  vertical-align: middle;
}
.radio_type:checked:after {
  content: "";
  width: 10px;
  height: 5px;
  border: 2px solid white;
  border-top: transparent;
  border-right: transparent;
  text-align: center;
  display: block;
  position: absolute;
  top: 6px;
  left: 5px;
  vertical-align: middle;
  transform: rotate(-45deg);
}
.radio_type:checked + label {
  color: #fc1c1c;
}

.shopCart {
  background-color: rgb(245, 245, 245);
  position: relative;
  height: calc(100vh - 55rem);
  overflow: auto;
  .title {
    // padding: 10rem;
    line-height: 44rem;
    height: 44rem;
    background-color: #fff;
    display: flex;
    justify-content: space-between;
    padding: 0 10rem;
    p {
      text-align: center;
      font-size: 16rem;
      color: #333;
    }
    span {
      font-size: 14rem;
    }
  }
  .content {
    margin-top: 10rem;
    margin: 10rem 0;
    ul.list {
      margin: 0 10rem;
      li {
        background-color: #fff;
        margin-bottom: 10rem;
        border-radius: 10rem;
        .store-title {
          display: flex;
          justify-content: left;
          align-items: center;
          font-size: 14rem;
          color: #2d2d2d;
          font-weight: bold;
          padding: 10rem;
          border-bottom: 1px solid rgb(245, 245, 245);
          img {
            width: 17rem;
            height: 16rem;
          }
          p {
            margin: 0 10rem;
          }
          sapn {
          }
        }
        ul.goods-content {
          padding: 10rem;
          li {
            display: flex;
            align-items: center;
            height: 100rem;
            margin-bottom: 20rem;
            > input {
            }
            img {
              width: 100rem;
              height: 100rem;
              border-radius: 10rem;
              margin: 0 10rem;
            }
            .detail {
              flex-grow: 1;
              display: flex;
              flex-direction: column;
              justify-content: space-between;
              height: 100%;
              .detail-title {
                font-size: 13rem;
                p {
                  color: #333;
                  line-height: 1.5em;
                }
                span {
                  color: #666;
                  margin-top: 5rem;
                }
              }
              .detail-action {
                display: flex;
                justify-content: space-between;
                align-items: center;
                span {
                  font-size: 17rem;
                  color: #fc1c1c;
                }
                .stepper {
                  height: 23rem;
                  border: 1rem solid #eee;
                  display: flex;
                  align-items: center;
                  span {
                    width: 23rem;
                    color: #2d2d2d;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    border-right: 1rem solid #eee;
                    &:last-child {
                      border-right: none;
                      border-left: 1rem solid #eee;
                    }
                  }
                  input {
                    width: 36rem;
                    height: 23rem;
                    border: none;
                    box-sizing: border-box;
                    display: flex;
                    text-align: center;
                  }
                }
              }
            }
          }
        }
      }
    }
    .empty {
      padding: 40rem 0;
      display: flex;
      flex-direction: column;
      justify-content: left;
      align-items: center;
      img {
        width: 105rem;
      }
      p {
        font-size: 13rem;
        color: #999;
        margin-top: 15rem;
      }
      button {
        color: #fc1c1c;
        font-size: 14px;
        padding: 0 12px;
        height: 27px;
        background: rgba(252, 28, 28, 0.1);
        border-radius: 13px;
        margin-top: 10px;
        border: none;
        margin-top: 10rem;
      }
    }
  }
  .balance {
    height: 50rem;
    width: 100vw;
    position: fixed;
    bottom: 55rem;
    left: 0;
    background-color: #fff;
    display: flex;
    align-items: center;
    justify-content: space-between;
    border-bottom: 1px solid rgb(245, 245, 245);
    padding: 0 10rem;
    box-sizing: border-box;
    .left {
      font-size: 13rem;
      color: #666;
      display: flex;
      align-items: center;
      input {
        margin-right: 5rem;
      }
    }
    .right {
      span {
        font-size: 13rem;
        color: #2d2d2d;
        &:nth-child(2) {
          font-size: 17rem;
          color: #fc1c1c;
        }
      }
      button {
        background: linear-gradient(90deg, #fc1f1d, #fd7326);
        border: none;
        border-radius: 20rem;
        height: 35rem;
        color: #fff;
        padding: 10rem 30rem;
        font-size: 14rem;
        margin-left: 20rem;
      }
    }
    .right-del-cart {
      display: flex;
      span {
        margin-left: 10rem;
        height: 30rem;
        width: 100rem;
        color: #fd7326;
        display: flex;
        justify-content: center;
        align-items: center;
        border: 1rem solid #fd7326;
        border-radius: 20rem;
        box-sizing: border-box;
        &:last-child {
          color: #fc1c1c;
          border: 1rem solid #fc1c1c;
        }
      }
    }
  }

  .bottom {
    width: 100vw;
    height: 55rem;
  }
}
</style>